<!--
 * @Author: C.
 * @Date: 2023-03-31 09:55:07
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #title="{ model, field }">
        <a-input v-model:value="model[field]">
          <template #addonAfter> {{ t(model[field] || '--') }} </template>
        </a-input>
      </template>
      <template #parentMenu="{ model, field }">
        <TreeSelect
          :treeData="treeData"
          v-model:value="model[field]"
          :fieldNames="{
            label: 'title',
            value: 'id',
          }"
        >
          <template #title="{ title }"> {{ t(title) }} </template>
        </TreeSelect>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { TreeSelect } from 'ant-design-vue';

  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { getMenuList, saveMenu } from '/@/api/work/system/menu';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { omit } from 'lodash-es';
  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm, TreeSelect },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref([]);
      const { t } = useI18n();
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        // console.log(data.record);

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        const res = await getMenuList();
        treeData.value = res.Items;
        // updateSchema({
        //   field: 'parentMenu',
        //   componentProps: { treeData: res.Items },
        // });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          await saveMenu(omit(values, 'copyMenu'));

          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit, treeData, t };
    },
  });
</script>
